package com.gin.kotlin.no_gay_alliance.base

import android.content.Context
import android.content.DialogInterface
import android.text.Html
import android.text.method.LinkMovementMethod
import android.util.Log
import android.widget.TextView
import androidx.datastore.preferences.core.Preferences
import com.tencent.bugly.crashreport.CrashReport
import io.reactivex.rxjava3.core.Single


class BuglyUtils {
    companion object {
        /**
         * bugly开启状态的key
         */
        private const val KEY_ENABLE = "enable"

        private const val KEY_SHOWN = "shown"
        /**
         * bugly授权弹窗是否已显示过的key
         */
        private const val MESSAGE_LAUNCH = "BUGLY SDK 启动"
        private const val TAG = "Bugly"
        private const val DATASTORE_NAME = "BUGLY"
        private const val MESSAGE =
            "本APP整合了BUGLY SDK用于收集APP运行时的错误信息，需要获得您的授权。请阅读以下规则，仅当您提供授权时SDK才会被激活，您后续也可以在‘设置’界面变更您的授权。"
        const val TIPS = "用于收集APP运行时的错误信息: "
        const val LINK = "<a href='https://document-75651.gzc.vod.tencent-cloud.com/70270bcd-a108-48d0-822c-5b98305c7ada.pdf'>Bugly SDK个人信息保护规则</a>"

        fun setEnable(value: Boolean, context: Context): Single<Preferences> {
            if (value) init(context)
            return NamedDataStore.getInstance(DATASTORE_NAME).set(KEY_ENABLE, value)
        }

        fun getEnable() = NamedDataStore.getInstance(DATASTORE_NAME).get(KEY_ENABLE, false)

        /**
         * 检查是否授权及是否弹窗请求授权
         * @param context Context
         */
        fun check(context: Context) {
            Log.d(TAG, "检查Bugly设置")
            val dataStore = NamedDataStore.getInstance(DATASTORE_NAME)
            //检查是否已显示过弹窗
            val shown = dataStore.get(KEY_SHOWN, false)

            if (shown) {
                //已显示过则按照授权结果决定是否启动BUGLY
                if (getEnable()) init(context)
            } else {


                val tv = TextView(context).also {
                    it.text = Html.fromHtml(LINK, Html.FROM_HTML_MODE_COMPACT)
                    it.movementMethod = LinkMovementMethod.getInstance()
                }
                //未显示过则弹窗请求授权
                AlertDialogUtils.builder(context, "Bugly SDK", MESSAGE, tv) { _, which ->
                    if (which == DialogInterface.BUTTON_POSITIVE) {
                        Log.d(TAG, "用户已授权")
                        setEnable(true, context)
                    }
                }
                    .setOnDismissListener { dataStore.set(KEY_SHOWN, true) }
                    .create()
                    .also { it.setCanceledOnTouchOutside(false) }
                    .show()

            }
        }

        /**
         * 初始化
         * @param context Context
         */
        private fun init(context: Context) {
            Log.d(TAG, MESSAGE_LAUNCH)
            CrashReport.initCrashReport(context.applicationContext)
        }
    }
}